<template>
  <div>
    <map-top-menu @startAnimation="startAnimation" :address="address" :facilityNum="facilityNum" :facilityName="facilityName"></map-top-menu>
    <div id="container" class="amap-wrapper">
      <old-time-info-window ref="infoWindow" @clickshow="showInfo" @closeInfoWindow="closeInfoWindow" :info="info"></old-time-info-window>
      <el-button round class="input-card" @click="onClickdefault">{{ israngingTool ? '關閉' : '開啟' }}測距</el-button>
      <span class="timer"><span class="green">{{ countdown }}</span>秒後刷新</span>
    </div>
  </div>
</template>

<script>
  import OldTimeInfoWindow from './components/old-time-info-window'
  import MapTopMenu from './components/map-top-menu'
  import MapLoader from '@/assets/js/AMap.js'
  import { mapState } from 'vuex'

  export default {
    name: 'map-container',

    components: {
      [OldTimeInfoWindow.name]: OldTimeInfoWindow,
      [MapTopMenu.name]: MapTopMenu
    },

    props: {
      copyCountdown: {
        type: Number,
        default: () => 20,
        required: false
      }
    },

    data() {
      return {
        startDate: '',
        endDate: '',
        // map: null,
        info: '',
        infoBaseWindow: null,
        infoWindow: null,
        ruler: null,
        israngingTool: false,
        countdown: 20,
        firstCenter: [],
        lineArr: [
          // [116.478935, 39.997761],
        ],
        marker: null
      }
    },

    computed: {
      ...mapState({
        changeAssets: (state) => state.map.changeAssets,
      }),

      facilityNum() {
        return this.$route.query.facilityNum || ''
      },

      facilityName() {
        return this.$route.query.facilityName || ''
      },

      address() {
        return this.$route.query.address || ''
      }
    },

    created() {
      this.getData()
    },

    mounted() {
      MapLoader().then(AMap => {
        setTimeout(() => {
          this.createAmap() //加载地图
          this.countDown() //开启倒计时刷新
        })
      }, e => {
        console.log('地图加载失败', e)
      })
    },

    methods: {
      getData() {
        this.$store.dispatch('map/fetchTrackView', { facilityNum: this.facilityNum, startDate: this.startDate, endDate: this.endDate }).then(res => {
          this.loading = false
          let lgMap = res.result.list
          if(lgMap.length) {
            this.firstCenter = [lgMap[0].longitude, lgMap[0].latitude]
            lgMap.forEach(item => {
              this.lineArr.push([item.longitude ,item.latitude])
            })
          }
        }).catch(err => {
          this.loading = false
          this.$message.error('获取定位列表失败：' + err)
          return false
        })
      },

      createAmap() {
        this.map = new AMap.Map('container', {
          center: this.firstCenter, //地图中心区域位置
          zoom: 11,
          resizeEnable: true,
          viewMode: '2D',
          lang: 'zh_cn'
        })

        let scale = new AMap.Scale({
          visible: true
        })

        let toolBar = new AMap.ToolBar({
          visible: true
        })

        //自定义样式
        var startMarkerOptions = {
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: require('@/assets/img/start.png')
          })
        };
        var endMarkerOptions = {
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: require('@/assets/img/end.png')
          }),
          offset: new AMap.Pixel(-9, -31)
        };

        var midMarkerOptions = {
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: require('@/assets/img/mid.png')
          }),
          offset: new AMap.Pixel(-9, -31)
        };
        var lineOptions = {
          strokeStyle: "solid",
          strokeColor: "#FF33FF",
          strokeOpacity: 1,
          strokeWeight: 2
        };
        var rulerOptions = {
          startMarkerOptions: startMarkerOptions,
          midMarkerOptions: midMarkerOptions,
          endMarkerOptions: endMarkerOptions,
          lineOptions: lineOptions
        };
        this.ruler = new AMap.RangingTool(this.map, rulerOptions);

        let mapType = new AMap.MapType({
          defalutType: 0,
          showTraffic: true,
          showRoad: true
        })

        //统一图标样式
        var icon = new AMap.Icon({
          // size: new AMap.Size(48, 48),
          image: require('@/assets/img/automobile-offline-2.png'),
          imageSize: new AMap.Size(48, 48)
        })

        //几个点就给几个marker
        this.marker = new AMap.Marker({
          map: this.map,
          position: this.firstCenter, //点所在位置
          icon: icon, //修改图标
          autoRotation: true,
          // offset: new AMap.Pixel(-26, -13),
          // angle: 90,
        }).on('click', () => {
          this.infoWindow.open(this.map)
        });

        this.marker.on('moving', function(e) {
          passedPolyline.setPath(e.passedPath)
        })

        this.map.setFitView()

        //轨迹绘制
        var passedPolyline = new AMap.Polyline({
          map: this.map,
          // path: lineArr,
          strokeColor: "#28F",  //线颜色 #AF5
          // strokeOpacity: 1,     //线透明度
          strokeWeight: 6,      //线宽
          // strokeStyle: "solid"  //线样式
        });

        this.map.addControl(scale)
        this.map.addControl(toolBar)
        this.map.addControl(mapType)

        this.infoBaseWindow = new AMap.InfoWindow({
          position: this.firstCenter, //弹出窗口的位置
          content: this.facilityName
        })

        this.infoBaseWindow.open(this.map)

        this.infoWindow = new AMap.InfoWindow({
          isCustom: true, //是否自定义信息窗口（默认false，会有一个白框包裹）
          offset: new AMap.Pixel(15, -10),//偏移量
          position: this.firstCenter, //弹出窗口的位置
          content: this.$refs.infoWindow.$el
        })
      },

      showInfo(info) {
        console.log(1, info)
      },

      openInfoWindow() {
        this.infoWindow.open(this.map)
      },

      closeInfoWindow() {
        //关闭信息窗口
        this.infoWindow.close()
      },

      onClickdefault() {
        if(!this.israngingTool) {
          this.ruler.turnOn();
        } else {
          this.ruler.turnOff();
        }
        this.israngingTool = !this.israngingTool
      },

      countDown() {
        var i=this.copyCountdown
        this.countdown = this.copyCountdown
        const updateTime = () => {
          if(i==0){
            i=this.copyCountdown
            this.countdown = this.copyCountdown
          }
          i--
          this.countdown--
        }
        setInterval(updateTime,1000)
      },

      startAnimation() {
        this.marker.moveAlong(this.lineArr, 200);

      }
    }
  }

/**
 * <div style="position: absolute; bottom: 0px; left: 0px;">
    <div class="bottom-center amap-info-contentContainer">
      <div class="amap-info-content amap-info-outer">
        <div style="top:-132px; left: -145px;width:300px;">
          <div class="popover-header" style="background: #fff;">
            <b>序号5767</b>
          </div>
          <div class="popover-body">
            <table class="tl-f w-100" style="height:114px">
              <tbody>
                <tr>
                  <th width="70" title="定位类型">定位类型：</th>
                  <td title="卫星定位">卫星定位</td>
                  </tr>
                <tr>
                  <th title="定位时间">定位时间：</th>
                  <td title="2021-12-13 15:59:06">2021-12-13 15:59:06</td>
                </tr>
                <tr>
                  <th title="速度">速度：</th>
                  <td title="0KM/H">0KM/H</td>
                </tr>
                <tr>
                  <th title="定位地点">定位地点：</th>
                  <td id="td5798">香港特别行政区观塘区安达臣道,百佳超市东北214米</td>
                </tr>
            </tbody>
          </table>
        </div>
      </div>
      <a class="amap-info-close" href="javascript: void(0)" style="right: 20px;">×</a>
    </div>
    <div class="amap-info-sharp"></div>
  </div>
</div>
**/
</script>

<style scoped lang="scss">
  // @import "../../../assets/css/them.scss";
  /* 设置地图容器的长和宽,必不可少 */
  .amap-wrapper {
    min-width: 1000px;
    width: 100%;
    height: calc(100vh - 200px);
    min-height: 600px;
  }

  .input-card {
    position: fixed;
    right: 30px;
    z-index: 999;
    top: 350px;
  }

  /deep/ .amap-toolbar, /deep/ .amap-scalecontrol, /deep/ .amap-maptypecontrol, .input-card, /deep/ .amap-geolocation-con {
    z-index: 9 !important;
  }

  .timer {
    position: absolute;
    top: 10px;
    left: 100px;
    z-index: 20;
    background-color: rgba(255, 255, 255, .9);
    padding: 4px 8px;
    border: 1px solid rgba(0, 0, 0, .15);
    border-radius: 4px;
    box-shadow: 0px 1px 4px -1px #EEEEEE;

    .green {
      color: #4EAD5B;
      margin-right: 5px;
    }
  }

  /deep/ .amap-info-close {
    display: none;
  }

  /deep/ .amap-info-content {
    background-color: rgba(219, 53, 53, .9);
    border-color: #af2a2a;
    color: #fff;
  }

  /deep/ .bottom-center .amap-info-sharp {
    border-top: 10px solid #af2a2a;
  }

</style>
